<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 私海
 * @icon fa fa-user
 */
class Privatesea extends Backend
{
    protected $relationSearch = true;
    protected $SourceModel = null;
    protected $ReceiveModel = null;
    protected $RegionModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->ReceiveModel = model('Business.Receive');
        // 城市模型
        $this->RegionModel = model('Region.Region');
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('scource')
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('scource')
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function source()
    {
        $list = $this->SourceModel->order('id', 'desc')->select();
        $data = [];
        foreach ($list as $item) {
            $data[$item['name']] = $item['name'];
        }
        echo json_encode($data);
    }
    /**
     * 新增
     */
    public function add()
    {
        $genders = ['0' => '保密', '1' => '男', '2' => '女'];
        $auths = ['0' => '未认证', '1' => '已认证'];
        $deals = ['0' => '未成交', '1' => '已成交'];
        $sources = $this->SourceModel->all();
        $sourceList = [];
        foreach ($sources as $item) {
            $sourceList[$item['id']] = $item['name'];
        }
        $this->view->assign(["genders" => $genders, "sources" => $sourceList, "deals" => $deals, 'auths' => $auths]);
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error("参数不能为空");
            }

            $data = [
                'mobile' => $params['mobile'] ?? '',
                'nickname' => $params['nickname'] ?? '',
                'email' => $params['email'] ?? '',
                'gender' => $params['gender'] ?? 0,
                'auth' => $params['auth'] ?? 0,
                'sourceid' => $params['sourceid'] ?? 0,
                'money' => $params['money'] ?? 0,
                'deal' => $params['deal'] ?? 0,
                'adminid' => $this->auth->id
            ];
            $salt = randstr();
            $password = md5($params['mobile'] . $salt);
            $data['password'] = $password;
            $data['salt'] = $salt;
            $code = $params['code'];
            if ($code != null) {
                $parentpath = $this->RegionModel->where('code', $code)->value('parentpath');
                if ($parentpath) {
                    $addcode = explode(',', $parentpath);
                    $data['province'] = $addcode[0] ?? '';
                    $data['city'] = $addcode[1] ?? '';
                    $data['district'] = $addcode[2] ?? '';
                } else {
                    $this->error("修改失败,无该地区信息");
                }
            }
            $result = $this->model->validate('common/Business/Business')->save($data);
            if (!$result) {
                $this->error($this->model->getError());
            }
            $this->success();
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $genders = ['0' => '保密', '1' => '男', '2' => '女'];
        $auths = ['0' => '未认证', '1' => '已认证'];
        $deals = ['0' => '未成交', '1' => '已成交'];
        $sources = $this->SourceModel->all();
        $sourceList = [];
        foreach ($sources as $item) {
            $sourceList[$item['id']] = $item['name'];
        }
        
        $row = $this->model->find($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error("参数不能为空");
            }
            $data = [
                'id' => $ids,
                'mobile' => $params['mobile'] ?? '',
                'nickname' => $params['nickname'] ?? '',
                'email' => $params['email'] ?? '',
                'gender' => $params['gender'] ?? 0,
                'auth' => $params['auth'] ?? 0,
                'sourceid' => $params['sourceid'] ?? 0,
                'money' => $params['money'] ?? 0,
                'deal' => $params['deal'] ?? 0,
                'adminid' => $this->auth->id
            ];
            $code = $params['code'];
           
            if ($code != null) {
                $parentpath = $this->RegionModel->where('code', $code)->value('parentpath');
                if ($parentpath) {
                    $addcode = explode(',', $parentpath);
                    $data['province'] = $addcode[0] ?? '';
                    $data['city'] = $addcode[1] ?? '';
                    $data['district'] = $addcode[2] ?? '';
                } else {
                    $this->error("修改失败,无该地区信息");
                }
            }
            $result = $this->model->validate('common/Business/Business.add')->isUpdate()->save($data);
            if (!$result) {
                $this->error($this->model->getError());
            }
            $this->success();
        }
         // 处理地区数据回显
         $row['regionCode'] = $row['district'] ?: ($row['city'] ?: $row['province']);
        $this->view->assign(["genders" => $genders, "sources" => $sourceList, "deals" => $deals, 'auths' => $auths,'row'=>$row]);
        return $this->view->fetch();
    }
    public function del($ids=null){
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__('用户信息不存在'));
        }
        $result=$this->model->destroy($ids);
        if($result===false){
            $this->error("操作失败");
        }
        $this->success("操作成功");
    }
    // 回收
    public function recovery($ids=null){
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__('用户信息不存在'));
        }
        $this->model->startTrans();
        $this->ReceiveModel->startTrans();
        $result=$this->model->isUpdate()->save(['id' => $ids,'adminid'=>null]);
      
        if($result===false){
            $this->error("操作失败");
        }
        $ReceiveData = [
            'busid' => $ids,
            'applyid' => $this->auth->id,
            'status' => 'recovery',
        ];
        $Receiveresult = $this->ReceiveModel->validate('common/Business/Receive')->save($ReceiveData);
        if ($Receiveresult === false) {
            $this->model->rollback();
            $this->error('操作失败');
        }
        $this->model->commit();
        $this->ReceiveModel->commit();
        $this->success("操作成功");
    }
}
